package dao;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import model.Automovel;
import model.Cliente;
import model.Dependente;
import model.Funcionario;
import model.Montadora;
import model.Origem;
import model.Pedido;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author Renan
 */
public class HibernateUtil {

    private static SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public Session openSession() {
        if (sessionFactory == null) {
            getSessionFactory();
        }
        return sessionFactory.openSession();
    }
    
    public static SessionFactory getSessionFactory() {
        AnnotationConfiguration cfg = new AnnotationConfiguration();
            cfg.addAnnotatedClass(Funcionario.class);
            cfg.addAnnotatedClass(Cliente.class);
            cfg.addAnnotatedClass(Automovel.class);
            cfg.addAnnotatedClass(Montadora.class);
            cfg.addAnnotatedClass(Pedido.class);
            cfg.addAnnotatedClass(Dependente.class);
            cfg.addAnnotatedClass(Origem.class);
            sessionFactory = cfg.buildSessionFactory();
            return sessionFactory;
    }
}
